<template>
  <div>
    <Breadcrumb></Breadcrumb> 
    <!-- 产品搜索 -->
      <div class="header">
        <div class="form">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="产品名称">
              <el-input v-model="formInline.name" placeholder="产品名称" clearable />
            </el-form-item>
            <el-form-item label="添加时间">
              <el-date-picker v-model="formInline.date" type="date" placeholder="选择时间" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button type="primary" @click="onResolve">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="group">
          <el-button type="warning" @click="addData" :icon="Plus">添加商品</el-button>
          <el-button type="danger" @click="deleteData" :icon="Delete">批量删除</el-button>

        </div>
      </div>
      <!-- 产品列表 -->
      <div class="content">
        <el-table :data="tableData" style="width: 100%" border header-row-class-name="active-header"
          @select="getselectdata" @select-all="getallselect">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="商品编号" width="120" />
          <el-table-column label="商品名称" width="120" show-overflow-tooltip>
            <template #default="scope">
              <span style="color: blue;cursor: pointer;" @click="handlelook(scope.$index, scope.row)">{{
                scope.row.title}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="商品价格" width="120" />
          <el-table-column prop="category" label="商品类目" width="120" />
          <el-table-column label="添加时间">
            <template #default="scope">
              <span>{{ moment(scope.row.create_time).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sellPoint" label="商品卖点" width="120" show-overflow-tooltip />
          <el-table-column prop="descs" label="商品描述" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ removeHTMLTag(scope.row.descs) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" @click="handleEdit(scope.$index, scope.row)" :icon="Edit">
                编辑
              </el-button>
              <el-button type="danger" @click="handleDelete(scope.$index, scope.row)" :icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination class="page" :total="total" :pageSize="pageSize" @CurrentChange="CurrentChange" />
      </div>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance,computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const router=useRouter()
import moment from 'moment'//全局引入时在app原型上挂载
import { removeHTMLTag } from '@/utils/common.js'
//全局导入
const cxt = getCurrentInstance()
const API = cxt.appContext.config.globalProperties.$API
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
import { userowDataStore } from '@/store/modules/product';
const rowDataStore=userowDataStore()
onMounted(() => {
  projectList()
})
//跳转到编辑界面
const handleEdit = (index, row) => {
  //存储当前数据到pinia
  // console.log(row);
  rowDataStore.changeRowData(row)
  rowDataStore.changetitle('编辑')
  router.push('addproduct')
}

//单个产品删除
const handleDelete = async (index, row) => {
  const id=row.id
  // const result = await API.deleteItemById({ id })
  // console.log(result);
      ElMessageBox.confirm(
        '确认删除当前商品信息吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
        }
      )
        .then(async() => {
          const result = await API.deleteItemById({ id })
          if (result.status == 200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            //9%8=1 9-1=4
            // 总共多少页
            const totalPage = computed(() => Math.ceil(total.value / pageSize.value));
            // console.log(total.value % pageSize.value);
            // console.log(totalPage.value);
            // console.log(Current.value);
            if (total.value % pageSize.value === 1 && totalPage.value == Current.value) {
              Current.value = Current.value - 1 > 0 ? Current.value - 1 : 1;//最好>1 
            }
            projectList(Current.value)
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消删除',
          })
        })
  }
//获取产品列表数据
const tableData = reactive([])
const total = ref(10)
const pageSize=ref(1)
const projectList = async(page) => {
  let result = await API.projectList({page})
  if (result.status == 200) {
    tableData.splice(0, tableData.length);
    tableData.push(...result.data)
    total.value = result.total
    pageSize.value = result.pageSize
  } else {
    console.log('projectList获取失败');
    tableData.splice(0, tableData.length);
    total.value = 0
    pageSize.value = 0
  }
}

//处理分页器
const Current=ref('')
const CurrentChange = (page) => {
  Current.value=page
  projectList(page)
}

//搜索
const formInline = reactive({
  name: '',
  date: '',
})
const onSubmit = async () => {
  if (!formInline.name) {//点击空的查询按钮
    return;
  }
  const result = await API.search({ search: formInline.name })
  // console.log(result);
  if (result.status == 200) {
    tableData.splice(0, tableData.length);
    tableData.push(...result.result)
    total.value = result.result.length;
  } else {
    tableData.splice(0, tableData.length);
    total.value =0
  }
  formInline.name=''
}

//重置
const onResolve = () => {
  projectList(Current.value)
}

//跳转至添加商品界面
const addData = () => {
  rowDataStore.changetitle('添加')
  router.push('addproduct')
}

//批量删除
const ids=reactive([])
const deleteData = () => {
  ElMessageBox.confirm(
    '确认删除当前商品信息吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  )
    .then(async () => {
      let result = await API.batchDelete({ ids: ids.join(',') })
      if (result.status == 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        // 总共多少页
        const totalPage = computed(() => Math.ceil(total.value / pageSize.value));
        if (totalPage.value == Current.value && tableData.length == ids.length) {
          Current.value = Current.value - 1 > 0 ? Current.value - 1 : 1;//最好>1 
        }
        projectList(Current.value)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//复选框（单）
const getselectdata = (selection,row) => {
  // console.log(selection, '---', row);
  // console.log(row.id);
  ids.splice(0,ids.length)
  selection.forEach(ele => {
    ids.push(ele.id)
  });
}
//复选框（多）
const getallselect = (selection) => {
  // console.log(selection);
  ids.splice(0, ids.length)
  selection.forEach(ele => {
    ids.push(ele.id)
  });
}
//查看详情页面
const handlelook = (index,row) => {
  console.log('跳转详情页面', row);
  rowDataStore.changeRowData(row)
  rowDataStore.changetitle('详情')
  router.push('addproduct')
}
</script>

<style lang="less" scoped>
.header {
  background: #fff;
  margin-bottom: 20px;
  padding: 10px;

  .demo-form-inline {
    .el-form-item {
      margin-right: 20px;
      margin-bottom: 16px;

      .el-input {
        --el-input-width: 220px;
      }
    }
  }

  .group {
    padding: 10px;
    border: 1px solid #eee;
  }
}

.content {
  background: #fff;

  :deep(.active-header) {
    color: #333
  }

  :deep(.el-table__cell) {
    text-align: center;
  }
  .page {
    padding: 20px;
  }
}
</style>